package com.serkol.ams.security;



import com.serkol.ams.security.filter.CheckTokenFilter;
import com.serkol.ams.security.handler.AnonymousAuthenticationHandler;
import com.serkol.ams.security.handler.CustomerAccessDeniedHandler;
import com.serkol.ams.security.handler.LoginFailureHandler;
import com.serkol.ams.security.handler.LoginSuccessHandler;
import com.serkol.ams.security.service.CustomerUserDetailsService;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig {

    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private CheckTokenFilter checkTokenFilter;

    /**
     * 注入加密类
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception{
//        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class)
//                  .authorizeRequests().requestMatchers()
//                // ... other configurations
//                .antMatchers("/v2/api-docs", "/swagger-resources", "/swagger-ui/**", "/*").permitAll();


        httpSecurity
                // 禁用basic明文验证
                .httpBasic(it -> it.disable())
                // 前后端分离架构不需要csrf保护
                .csrf(it -> it.disable())
                // 禁用默认登录页
                .formLogin(it -> it.disable())
                // 禁用默认登出页
                .logout(it -> it.disable())
                // 设置异常的EntryPoint，如果不设置，默认使用Http403ForbiddenEntryPoint
                .exceptionHandling(exceptions -> {
                    // 401
                    exceptions.authenticationEntryPoint(anonymousAuthenticationHandler);
                    // 403
                    exceptions.accessDeniedHandler(customerAccessDeniedHandler);
                })
                // 前后端分离是无状态的，不需要session了，直接禁用。
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorizeHttpRequests -> authorizeHttpRequests
                        // 允许匿名访问
                        .requestMatchers("/webjars/**","/doc.html","/v3/api-docs/**","/v2/api-docs/**", "/swagger-resources", "/swagger-ui/**", "/*","/sys/authority/users/getAppLogin","/login").permitAll()
                        // 允许所有OPTIONS请求
                      //  .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        // 允许 SpringMVC 的默认错误地址匿名访问
                        .requestMatchers("/error").permitAll()
                        // 允许任意请求被已登录用户访问，不检查Authority
                        .anyRequest().authenticated())
               // .authenticationProvider(authenticationManager())
                // 加我们自定义的过滤器，替代UsernamePasswordAuthenticationFilter
                .addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();


    }
 @Bean
    public AuthenticationManager authenticationManager() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(customerUserDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        ProviderManager pm = new ProviderManager(daoAuthenticationProvider);
        return pm;
    }
/*        @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(checkTokenFilter(), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                // ... other configurations
                .antMatchers("/v2/api-docs", "/swagger-resources", "/swagger-ui/**").permitAll(); // Allow access to Swagger endpoints
    }*/
}
